<?php

namespace App\Http\Controllers;

use App\Models\Article;



use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class TestController extends Controller
{
    public function upload(){
        $rel = Article::where(array('id'=>'3'))->first()->content;
        $xx = explode('<img src="/Uploads/image/',$rel);
        $arrxx = array();
        for( $i=1;$i<count($xx);$i++){
            $arrxx[] = "C:\Users\admin\PhpstormProjects\untitled\lara4\laravel\public\Uploads\image\\".str_replace('/','\\',mb_substr($xx[1],0,29));
        }
        $accessKey = 'REGLFp0vy53PLg-szJvTHE_NJhBKTSyQ8fTVeA-S';
        $secretKey = 'YR2jV9TCzxOPNtOtqhd4yOk33zS2iX5qYNnMcDKx';
        $bucket = 'licheng';
        $arr = array();
        for( $i=0;$i<count($arrxx);$i++ ){
            $auth = new Auth($accessKey, $secretKey);
            $token = $auth->uploadToken($bucket);
            $filePath = $arrxx[$i];
            $key = time().rand(999,9999).".jpg";
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return back()->with('error','图片上传出错，请重试') ;
            } else {
                $arr[] = $str = "<img src='http://ohv2zs4x6.bkt.clouddn.com/".$ret['key']."'/>";
                $rel = preg_replace("/<img src=\".+?\"\/\>/s", "$str", $rel,1);
            }
        }
        $rel = Article::where(array('id'=>'3'))->update(array('content'=>$rel));
        dd($rel);

//        return view('tets');
    }

    public function postUpload(Request $request){
        $arrImg = ['image/gif','image/jpeg','image/png','image/x-icon'];
        $file = $request->file('file') ;
        if(!in_array($file[0]->getmimeType(),$arrImg)){
            return back()->with('error','请上传正确的图片格式') ;
        }
        if(empty($file[0])){
            return back()->with('error','缩略图必须上传') ;
        }
        $accessKey = 'REGLFp0vy53PLg-szJvTHE_NJhBKTSyQ8fTVeA-S';
        $secretKey = 'YR2jV9TCzxOPNtOtqhd4yOk33zS2iX5qYNnMcDKx';
        $bucket = 'licheng';
        $arr = array();
        for( $i=0;$i<count($file);$i++ ){
            $auth = new Auth($accessKey, $secretKey);
            $token = $auth->uploadToken($bucket);
            $filePath = $file[$i]->getRealPath();
            $key = time().rand(999,9999).".jpg";
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return back()->with('error','图片上传出错，请重试') ;
            } else {
                $arr[]='http://ohv2zs4x6.bkt.clouddn.com/'.$ret['key'];
            }
        }
        dd($arr);


    }
}
